package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;

import java.io.IOException;

@Slf4j
@Component
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;


    /**
     * 注册成功初始化用户账户信息
     * /在RabbitMQ里面监听消息
     */

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(exchange = @Exchange(value = MqConst.EXCHANGE_USER,
            durable = "true"),value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true"),
            key = {MqConst.ROUTING_USER_REGISTER}
    ))
    public void addUserAccount(Long userId, Message message, Channel channel){
        System.out.println("用户注册成功，用户id："+userId);
        try {
            if (null != userId){
                userAccountService.addUserAccount(userId);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        try {
//        手动应答,确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
